package com.gcxy.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gcxy.dto.Account.*;
import com.gcxy.entity.AccountInfo;
import com.gcxy.mapper.AccountInfoMapper;
import com.gcxy.service.AccountInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gcxy.utils.JwtTokenUtil;
import com.gcxy.utils.Md5Util;
import com.gcxy.utils.R;
import com.gcxy.utils.ResultCondeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author wlp
 * @since 2023-12-20
 */
@Service
public class AccountInfoServiceImpl extends ServiceImpl<AccountInfoMapper, AccountInfo> implements AccountInfoService {
    @Autowired
    private AccountInfoMapper accountInfoMapper;

    /**
     * @param requestBody
     * @return
     */
    @Override
    public R login(LoginDto requestBody) {
        AccountInfo accountInfo = accountInfoMapper.selectById(requestBody.getAccount());
        if (accountInfo.getAccState() == 1) {
            boolean result = Md5Util.passwordVerify(requestBody.getPassword(), accountInfo.getPassword());
            if (result) {
//                AccountInfo accountInfo = accountInfoMapper.selectById(requestBody.getAccount());
                String token = JwtTokenUtil.buildJwt(accountInfo.getAccName(), accountInfo.getAccount());
                Map data = new HashMap();
                data.put("token", token);
                return R.Success(data);
            } else {
                return R.Failed(0, "账号或密码错误");
            }
        } else {
            return R.Failed(0, "账号被封禁");
        }

    }

    /**
     * @param requestBody
     * @return
     */
    @Override
    public R register(RegisterDto requestBody) {
        System.out.println("错误在一开始");
        System.out.println(requestBody.getAccount());
        AccountInfo accountInfo = accountInfoMapper.selectById(requestBody.getAccount());
        System.out.println("accountInfo = " + accountInfo);
        if (accountInfo == null) {
            System.out.println("错误在判断");
            String pwd = Md5Util.md5(requestBody.getPassword());
            AccountInfo accountinfo1 = AccountInfo.builder()
                    .account(requestBody.getAccount())
                    .password(pwd)
                    .accName(requestBody.getAccName())
                    .accPhone(requestBody.getAccPhone())
                    .accState(1)
                    .createTime(LocalDateTime.now())
                    .updateTime(LocalDateTime.now())
                    .build();
            int count = accountInfoMapper.insert(accountinfo1);
            if (count > 0) {
                System.out.println("错误在执行insert");
                return R.Success();
            } else {
                return R.Failed(0, "注册失败");
            }
        } else {
            return R.Failed(0, ResultCondeEnum.USERNAME_USED.getMessage());
        }
    }

    @Override
    public R current(String token) {
        if (token == null) {
            return R.Failed("token异常");
        }
        String userId = JwtTokenUtil.getUserId(token);
        if (userId != null) {
            LambdaQueryWrapper<AccountInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(AccountInfo::getAccount, userId);
            AccountInfo accountInfo = accountInfoMapper.selectOne(lambdaQueryWrapper);
            accountInfo.setPassword("");
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            Map data = new HashMap<>();
            data.put("account", accountInfo.getAccount());
            data.put("accName", accountInfo.getAccName());
            data.put("accState", accountInfo.getAccState());
            data.put("createTime", accountInfo.getCreateTime().format(formatter));
            data.put("updateTime", accountInfo.getUpdateTime().format(formatter));
            return R.Success(data);
        } else {
            return R.Failed(0, "获取失败");
        }
    }

    @Override
    public R addAccount(InsertDto requestBody) {
        LambdaQueryWrapper<AccountInfo> accountInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        accountInfoLambdaQueryWrapper.eq(AccountInfo::getAccPhone, requestBody.getAccPhone());
        AccountInfo accountInfo = accountInfoMapper.selectOne(accountInfoLambdaQueryWrapper);
        if (accountInfo != null) {
            return R.Failed(0, "手机号已存在");
        }

        Long count = accountInfoMapper.selectCount(null);
        count++;
        String account = "YZ000" + count;
        String ps = Md5Util.md5(requestBody.getAccPhone().substring(requestBody.getAccPhone().length() - 6));
        AccountInfo accountInfo1 = AccountInfo.builder()
                .account(account)
                .accName(requestBody.getAccName())
                .accPhone(requestBody.getAccPhone())
                .accState(requestBody.getAccState())
                .password(ps)
                .createTime(LocalDateTime.now())
                .updateTime(LocalDateTime.now())
                .build();
        int insert = accountInfoMapper.insert(accountInfo1);
        if (insert > 0) {
            return R.Success();
        }
        return R.Failed(0, "新增失败");
    }

    @Override
    public R pageAccount(AccountPageDto requestBody) {
        QueryWrapper<AccountInfo> queryWrapper = new QueryWrapper<>();
        Page<AccountInfo> page = new Page<>(requestBody.getPageNumber(), requestBody.getPageSize());
        queryWrapper.like(requestBody.getAccName() != null && !"".equals(requestBody.getAccName()), "acc_name", requestBody.getAccName())
                .like(requestBody.getAccPhone() != null && !"".equals(requestBody.getAccPhone()), "acc_phone", requestBody.getAccPhone())
                .like(requestBody.getAccState() != null, "acc_state", requestBody.getAccState())
                .orderByDesc("create_time");
        ;
        accountInfoMapper.selectPage(page, queryWrapper);
        for (AccountInfo p : page.getRecords()) {
            p.setPassword("");
        }
        return R.Success(page);
    }

    @Override
    public R updateAccount(UpdateDto requestBody) {
        LambdaQueryWrapper<AccountInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(AccountInfo::getAccPhone, requestBody.getAccPhone());
        AccountInfo accountInfo = accountInfoMapper.selectOne(lambdaQueryWrapper);
        if (accountInfo != null && !accountInfo.getAccount().equals(requestBody.getAccount())) {
            return R.Failed(0, "手机号已存在");
        }
        String ps = Md5Util.md5(requestBody.getAccPhone().substring(requestBody.getAccPhone().length() - 6));
        AccountInfo accountInfo1 = AccountInfo.builder()
                .account(requestBody.getAccount())
                .accName(requestBody.getAccName())
                .accPhone(requestBody.getAccPhone())
                .password(ps)
                .accState(requestBody.getAccState())
                .updateTime(LocalDateTime.now())
                .build();
        int i = accountInfoMapper.updateById(accountInfo1);
        if (i > 0) {
            return R.Success();
        } else {
            return R.Failed(0, "修改失败");
        }

    }

    @Override
    public R updateState(String account, Integer accState) {
        LambdaQueryWrapper<AccountInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AccountInfo::getAccount, account);
        AccountInfo accountInfo = AccountInfo.builder()
                .accState(accState)
                .build();
        int update = accountInfoMapper.update(accountInfo, queryWrapper);
        if (update > 0) {
            return R.Success();
        }
        return R.Failed(0, "修改失败");
    }
}
